﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace OnlineMusic.lrc
{
    abstract class LrcBase : LrcAdapter
    {
        public abstract string FindLrc(string title, string singer);
        public List<LrcText> ReadLrc(string lrc)
        {
            List<LrcText> lrcs = new List<LrcText>();
            StringReader reader = new StringReader(lrc);
            string tmp = "";

            do
            {
                tmp = reader.ReadLine();
                if (tmp == null)
                    break;
                Regex reg = new Regex("\\d\\d:\\d\\d\\.\\d\\d");
                MatchCollection matches = reg.Matches(tmp);
                Regex regtext = new Regex("\\[\\d\\d:\\d\\d\\.\\d\\d\\]");
                string text = regtext.Replace(tmp, "");
                foreach (Match match in matches)
                {
                    LrcText lt = new LrcText();
                    lt.Time = ToTime(match.Value);
                    lt.Text = text;
                    lrcs.Add(lt);
                }
            } while (tmp != null);
            lrcs.Sort(new LrcCompare());
            return lrcs;
        }
        private int ToTime(string timestr)
        {
            string m = timestr.Substring(0, 2);
            string s = timestr.Substring(3, 2) + timestr.Substring(6);
            return Convert.ToInt16(m) * 60000 + Convert.ToInt16(s) * 10;
        }


        public string wget(String url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = WebRequestMethods.Http.Get;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string html = reader.ReadToEnd();
            reader.Close();
            response.Close();
            return html;
        }
        public string LoadLrc(string lrcurl)
        {
            if (lrcurl == null || lrcurl.Equals(""))
            {
                return "";
            }

            return wget(lrcurl);
        }
    }
}
